package com.xqq.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.xqq.utils.CommonUtil.calculateDistance;

public class DistanceCheck {

    public static void main(String[] args) {
        String filePath = "C:\\Users\\87374\\Desktop\\无标题.csv";
        List<String> positions = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            boolean isFirstLine = true;
            int positionIndex = -1;
            // 读取文件的每一行
            while ((line = br.readLine()) != null) {
                // 跳过标题行
                if (isFirstLine) {
                    // 获取列索引
                    String[] headers = line.split(",");
                    for (int i = 0; i < headers.length; i++) {
                        if (headers[i].trim().equals("position")) {
                            positionIndex = i;
                            break;
                        }
                    }
                    isFirstLine = false;
                    continue;
                }
                positionIndex=3;

                // 按逗号分割数据
                String[] columns = line.split(",");
                if (positionIndex != -1 && columns.length > positionIndex) {
                    // 获取 "position" 列的数据并按分号分割后添加到 List 中
                    String Longitude = columns[positionIndex].trim().replace("\"","");
                    String Latitude = columns[positionIndex+1].trim().replace("\"","");
                    positions.addAll(Arrays.asList(Longitude+","+Latitude));
                }
            }
            List<Double> distances = new ArrayList<>();
            for (int i = 0; i < positions.size()-1; i++) {
                String[] point1 = positions.get(i).split(",");
                String[] point2 = positions.get(i + 1).split(",");
                // 转换为经纬度
                double lat1 = Double.parseDouble(point1[1].trim());
                double lon1 = Double.parseDouble(point1[0].trim());
                double lat2 = Double.parseDouble(point2[1].trim());
                double lon2 = Double.parseDouble(point2[0].trim());

                // 计算两点之间的距离
                double distance = calculateDistance(lon1, lat1, lon2, lat2);
                distances.add(distance);
//                System.out.println(distance);
            }
            calculateStatistics(distances);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void calculateStatistics(List<Double> distances) {
        if (distances == null || distances.isEmpty()) {
            System.out.println("The distance list is empty.");
            return;
        }else {
            System.out.println("共计点位："+distances.size()+" 个");
        }

        // 平均值
        double sum = 0;
        for (double distance : distances) {
            sum += distance;
        }
        double average = sum / distances.size();
        System.out.println("Average: " + average);

        // 最大值
        double max = Collections.max(distances);
        System.out.println("Max: " + max);

        // 最小值
        double min = Collections.min(distances);
        System.out.println("Min: " + min);

        // 中位数
        List<Double> sortedDistances = new ArrayList<>(distances);
        Collections.sort(sortedDistances);
        double median = calculateMedian(sortedDistances);
        System.out.println("Median: " + median);

        // 区间统计
        calculateIntervals(sortedDistances, min, max);
    }

    // 计算中位数
    public static double calculateMedian(List<Double> sortedList) {
        int size = sortedList.size();
        if (size % 2 == 1) {
            return sortedList.get(size / 2);
        } else {
            return (sortedList.get(size / 2 - 1) + sortedList.get(size / 2)) / 2.0;
        }
    }

    // 区间统计
    public static void calculateIntervals(List<Double> sortedDistances, double min, double max) {
        Map<String, Integer> intervalCounts = new LinkedHashMap<>();
        int total = sortedDistances.size();

        // 设置区间
        for (double i = min; i < max; i += 20) {
            String intervalLabel = String.format("[%.1f, %.1f)", i, i + 20);
            intervalCounts.put(intervalLabel, 0);
        }

        // 添加最后一个区间，包含最大值
        String lastIntervalLabel = String.format("[%.1f, %.1f]", max - (max % 20), max);
        intervalCounts.put(lastIntervalLabel, 0);

        // 统计数据分布到区间
        for (double distance : sortedDistances) {
            for (String interval : intervalCounts.keySet()) {
                String[] bounds = interval.replace("[", "").replace(")", "").replace("]", "").split(", ");
                double lower = Double.parseDouble(bounds[0]);
                double upper = Double.parseDouble(bounds[1]);

                if ((distance >= lower && distance < upper) || (distance == max && interval.equals(lastIntervalLabel))) {
                    intervalCounts.put(interval, intervalCounts.get(interval) + 1);
                    break;
                }
            }
        }

        // 输出区间统计
        System.out.println("Interval Statistics:");
        for (Map.Entry<String, Integer> entry : intervalCounts.entrySet()) {
            String interval = entry.getKey();
            int count = entry.getValue();
            double percentage = (count * 100.0) / total;
            System.out.printf("%s: %d (%.2f%%)%n", interval, count, percentage);
        }
    }
}
